#!/bin/sh

FILE=$1
DEST="../${BUILDS}"
ERROR='False'

cd $THIRD_PARTY

if [ ! -f $FILE ]; then
    echo
    echo "Could not find downloaded file ${FILE}; skipping..."
    echo
    exit 0
fi

echo "Installing $FILE ..."

# check for file extensions and unzip
DIR=''
if [[ `echo $FILE | sed -n '/gz$/{p;q;}'` == "$FILE" ]]; then
    DIR=`tar xvfz $FILE | tail -1 | awk -F/ '{print $1}'`
elif [[ `echo $FILE | sed -n '/bz2$/{p;q;}'` == "$FILE" ]]; then
    DIR=`tar xvfj $FILE | tail -1 | awk -F/ '{print $1}'`
fi
if [[ "$DIR" == '' ]]; then
    echo
    echo "Could not determine uncompressed directory name!"
    echo
    echo "Aborting ..."
    echo
    exit 1
fi
if [[ ! -d ${DEST}/${DIR} ]]; then
    mv $DIR ${DEST}/ 
else
    rm -rf $DIR
fi

# change dir
cd ${DEST}/${DIR}

# build
if [[ `echo $FILE | sed -n '/^Python-/{p;q;}'` == "$FILE" ]]; then
    ./configure --prefix=${PREFIX} || ERROR='True'
    make || ERROR='True'
    make install || ERROR='True'
    if [[ "$ERROR" == "True" ]]; then
        echo
        echo "Error installing Python!"
        echo 
        echo "Aborting..."
        exit 1
    else
        export ZOPE_PYTHON=${PREFIX}/bin/python
    fi
elif [[ `echo $FILE | sed -n '/^Zope-/{p;q;}'` == "$FILE" ]]; then
    ./configure --prefix=${PREFIX} --with-python=${PYTHON} || ERROR='True'
    make || ERROR='True'
    make install || ERROR='True'
    ${PREFIX}/bin/mkzopeinstance.py --dir ${PREFIX} \
        --user ${USERNAME}:${PASSWORD} || ERROR='True'
    if [[ "$ERROR" == "True" ]]; then
        echo
        echo "Error installing Zope!"
        echo
        echo "Aborting..."
        exit 1
    fi

# Plone requires PIL
elif [[ `echo $FILE | sed -n '/^Imaging-/{p;q;}'` == "$FILE" ]]; then
    ${PYTHON} setup.py install || ERROR='True'
    if [[ "$ERROR" == "True" ]]; then
        echo
        echo "Error installing PIL!"
        echo
        echo "Aborting..."
        exit 1
    fi

elif [[ `echo $FILE | sed -n '/^Plone-/{p;q;}'` == "$FILE" ]]; then
    mv ./* ${PREFIX}/Products/ || ERROR='True'
    # remove old Products
    rm -rf ${PREFIX}/Products/Five
    if [[ "$ERROR" == "True" ]]; then
        echo
        echo "Error installing Plone!"
        echo
        echo "Aborting..."
        exit 1
    fi

elif [[ `echo $FILE | sed -n '/^Five-/{p;q;}'` == "$FILE" ]]; then
    cd ../
    mv Five ${PREFIX}/Products/ || ERROR='True'
    if [[ "$ERROR" == "True" ]]; then
        echo
        echo "Error installing Five!"
        echo
        echo "Aborting..."
        exit 1
    fi
fi
